<template>
  <a-button type="primary" @click="open = true">
    <plus-outlined/>创建角色
  </a-button>
  <a-drawer title="创建角色" v-model:open="open" @close="closeModal" @ok="onSubmit" :width="520">
    <a-form :model="form"
            name="roleForm"
            ref="formRef"
            :rules="rules"
            :label-col="{span:4}"
            :wrapper-col="{span:17}">
      <a-form-item label="角色名称" name="role_name">
        <a-input v-model:value="form.role_name" placeholder="请输入角色名称" show-count :maxlength="10"/>
      </a-form-item>
      <a-form-item label="角色描述">
        <a-textarea v-model:value="form.description" placeholder="请输入角色描述"/>
      </a-form-item>
      <a-form-item label="角色样式">
        <use-color v-model:value="form.style"/>
      </a-form-item>
      <a-form-item label="角色权限" class="margin-bottom-sm"></a-form-item>
        <a-checkbox-group v-model:value="form.permissions">
        <div class="row" v-for="item in store.permissions">
          <div class="title">
            <a-checkbox :value="item.id">{{item.title}}</a-checkbox>
          </div>
          <div class="sub" v-if="item.children">
            <a-space>
              <a-checkbox v-for="permission in item.children" :value="permission.id">
                {{permission.title}}
              </a-checkbox>
            </a-space>
          </div>
        </div>
        </a-checkbox-group>
    </a-form>
    <template #footer>
      <a-flex justify="end" :gap="8">
        <a-button @click="closeModal">取消</a-button>
        <a-button type="primary" :loading="loading" @click="onSubmit">提交保存</a-button>
      </a-flex>
    </template>
  </a-drawer>
</template>
<script setup lang="ts">
import {PlusOutlined} from "@ant-design/icons-vue";
import {onMounted, reactive, ref, watch} from "vue";
import type {FormInstance} from "ant-design-vue";
import UseColor from "@/components/UseColor.vue";
import {getEnterpriseId, getUserId} from "@/plugin/auth";
import {roleCreate,roleUpdate,roleDetail} from "@/api/modules/permission";
import useMessage from "@/plugin/useMessage";
import {HttpResponse} from "@/api/request";
import {usePermissionStore} from '@/store/permission'

const store = usePermissionStore()

const formRef = ref<FormInstance>()
const emits = defineEmits(['ok'])
let open = defineModel('open',{default:false})
const roleId = defineModel('id',{default:0})
const form = reactive({
  id:0,
  user_id:getUserId(),
  role_name:'',
  enterprise_id:getEnterpriseId(),
  description:'',
  style:'',
  permissions:[]
})
let loading = ref<boolean>(false)
const rules = {
  role_name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  permissions:[
      {required:true,message:'请选择角色权限',trigger:'change'} ,
      {validator:()=>{
    if(form.permissions.workbench.length === 0 && form.permissions.admin.length === 0){
      return Promise.reject(new Error('请选择角色权限'))
    }else{
      return Promise.resolve()
    }
  }}]
}
const closeModal = () => {
  open.value = false
  formRef.value?.resetFields()
  roleId.value = 0
  form.permissions = []
}

onMounted(()=>{
  store.getPermissions()
})
const onSubmit = async () => {
  try {
    await formRef.value?.validateFields()
    loading.value = true
    let res:HttpResponse|any
      if(roleId.value === 0){
        delete form.id
        res = await roleCreate(form)
      }else {
        res = await roleUpdate(form)
      }
    if(res.code === 200){
      formRef.value?.resetFields()
      closeModal()
      emits('ok')
    }
    useMessage(res.code,res.message)
    setTimeout(() => {
      loading.value = false
    }, 1000)
  }catch (e){}
  finally {
    loading.value = false
  }
}
const getRoleData = async () => {
  const res = await roleDetail(roleId.value)
  if(res.code === 200){
    form.id = res.data.id
    form.role_name = res.data.role_name
    form.description = res.data.description
    form.style = res.data.style
    form.permissions = res.data.permissions
  }
}
watch(()=>roleId.value,()=>{
  if(roleId.value){
    getRoleData()
  }
})
</script>

<style scoped>
.row {
  width: 100%;
  border-radius: var(--border-radius);
  padding: 8px 12px;
  border: 1px solid var(--border-color);
}
.row+.row{
  border-top: 1px solid var(--border-color);
  margin-top: 8px;
}
.row>.sub{
  border-top: 1px dashed var(--border-color);
  padding-top: 8px;
  margin-top: 8px;
}
</style>